﻿//系统管理-->用户管理
//Create By:Cui 2014年9月19日12:09:48

//1.0 加载JqueryDatabase
jQuery(function ($) {
    var oTable1 = $('#sample-table-2').dataTable({
        "aoColumns": [
          { "bSortable": false },
          { "bSortable": true },
          { "bSortable": true },
          { "bSortable": true },
          { "bSortable": true },
          { "bSortable": true },
          { "bSortable": false },
        ],
        oLanguage: {
            "sProcessing": "正在加载中......",
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "对不起，查询不到相关数据！",
            "sEmptyTable": "表中无数据存在！",
            "sInfo": "当前显示： _START_ 到 _END_ 条，共 _TOTAL_ 条",
            "sInfoFiltered": "数据表中共为 _MAX_ 条记录",
            "sSearch": "",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            }
        },
        iDisplayLength: 30,
        bLengthChange: false
        
    });


    $('table th input:checkbox').on('click', function () {
        var that = this;
        $(this).closest('table').find('tr > td:first-child input:checkbox')
        .each(function () {
            this.checked = that.checked;
            $(this).closest('tr').toggleClass('selected');
        });

    });


    $('[data-rel="tooltip"]').tooltip({ placement: tooltip_placement });
    function tooltip_placement(context, source) {
        var $source = $(source);
        var $parent = $source.closest('table')
        var off1 = $parent.offset();
        var w1 = $parent.width();

        var off2 = $source.offset();
        var w2 = $source.width();

        if (parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2)) return 'right';
        return 'left';
    }


    $("#userGroupID").select2({
        placeholder: "点击选择（可多选）",
        width: "100% "
    });


})


window.onload = function () {
    
    //2.0 页面初始化
    //2.1 给table加按钮（增加，删除，刷新）
   
    $("td").addClass("tdBorder");


    //2.2 table表头上的样式
    $("#sample-table-2>thead tr>th").attr("style", "font-weight:bold;color:black;text-align:center");


    //2.3 table搜索样式
    $("#sample-table-2_filter label input").attr("placeholder", "搜索(多条件搜索中间用空格隔开)").attr("style", "width:50%");
    $("#sample-table-2_filter label").attr("style", "width:100%");
    $("#sample-table-2_filter").attr("style", "margin-right: -16px;");
    $("#sample-table-2_wrapper .row").first().children().eq(1).attr("style", "margin-top:-12px");
    $("#sample-table-2_wrapper").attr("style", "margin-top:-32px");
    $("#butadd").attr("style", "margin-top:-4px");

    //2.4 增加表单行间距样式
    $("div .modal-body .row:not(#iconr)").attr("style", "margin-top:7px;");
    $("div .modal-body .row .col-sm-3").attr("style", "margin-top:6px;text-align:right");
    $("div#myModal .modal-body .row i:lt(6)").attr("style", "margin-top:9px;text-align:right;");

    $("#form_field_select_4_chosen").attr("style", "width:100%");

    //2.5 按钮样式
    $("button.btn.btn-sm:gt(0)").attr("style", "margin:-5px 0px 0px 4px");

    //2.6 显示页数一行的样式
    $("#sample-table-2").next().find(".col-sm-6").eq(0).attr("style", "margin-left: -12px;margin-top: 5px;");
    $("#sample-table-2").next().find(".col-sm-6").eq(1).attr("style", "margin-left: 12px;margin-top: 0px;");


    //3.0   功能
    //3.1   删除
    $("#butdel").click(function delCheck() {
        var idString = "";
        $("table tbody input[type='checkbox']:checked").parent().parent().next().each(function () {
            idString += $(this).text() + ","
        });
        idString = idString.substring(0, idString.length - 1);
        if (idString.length == 0) {
            $.gritter.add({
                title: '消息提醒',
                text: '请选择要删除的项',
                class_name: 'gritter-info gritter-center'
            });
        }
        else {
            if (!confirm("确定删除")) { return; }
            $.ajax({
                url: "ToDelete",
                dataType: "Json",
                data: { idString: idString },
                Type: "Post",
                success: function (data) {
                    var json = eval(data);
                    if (json.result == "Success") {
                        $.gritter.add({
                            title: '消息提醒',
                            text: json.message,
                            class_name: 'gritter-info gritter-center'
                        });
                        history.go(0);
                    }
                    else {
                        $.gritter.add({
                            title: '消息提醒',
                            text: json.message,
                            class_name: 'gritter-info gritter-center'
                        });
                    }
                }
            });
        }
    });

    //3.2   刷新
    $("#buflush").click(function () {
        history.go(0);
    });
    //遮罩层div
    $("#bgdiv").attr("style", "display:none");
    //5.2   点击新增按钮
    //5.2.1 初始化新增
    function initForm() {
        $("div#myModal .modal-body .row i:lt(5)").attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
        $("div#myModal .modal-body .row input:not([autocomplete])").val("").removeAttr("style");
        //$("div#myModal .modal-body .row select:lt(1)").val("0").removeAttr("style");

        $("#but_saveadd").removeAttr("style");
        $("#but_savemodify").removeAttr("style").attr("style", "display:none");

        $("#LookPWD").attr("class", "btn btn-minier btn-white icon-eye-open");
        $("#UserPassword").attr("type", "password")
        $("#UserPassword1").attr("type", "password")

        //初始化多选框
        $("#userGroupID").select2("val", "");
    }
    //5.2.2 点击新增按钮，初始化模态窗口
    $("#butadd").click(function () {
        initForm();
        $("#myModal").modal();
    });
    //5.2.3 验证表单
    $("#NickName").focus(function () {
        $(this).removeAttr("style");
        $(this).parent().next().attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
    });
    $("#NickName").blur(function () {
        var reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]{2,5}$/;  //长度为2-5的汉英文数字下滑线
        var obj = $(this).val();
        if (!reg.test(obj)) {
            $(this).attr("style", " border-color: red;");
            $(this).parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");

        }
    });

    //$("#s2id_autogen1").focus(function () {
    //    $(this).removeAttr("style");
    //    $(this).parent().parent().parent().parent().next().attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
    //});    //选择用户组
    //$("#s2id_autogen1").blur(function () {
    //    if ($("#userGroupID").select2("val").length==0) {
    //        $(this).attr("style", " border-color: red;");
    //        $(this).parent().parent().parent().parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");

    //    }
    //});

    $("#s2id_autogen1").attr("style", "width: 302px; height: 31px; font-size: 15px; font-family: 微软雅黑;");

    $("#UserName").focus(function () {
        $(this).removeAttr("style");
        $(this).parent().next().attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
    });
    $("#UserName").blur(function () {
        var reg = /^[a-zA-Z]{3,16}$/;
        var obj = $(this).val();
        if (!reg.test(obj)) {
            $(this).attr("style", " border-color: red;");
            $(this).parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");

        }
    });

    $("#UserPassword").focus(function () {
        $(this).removeAttr("style");
        $(this).parent().next().attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
    });
    $("#UserPassword").blur(function () {
        var reg = /^\w{6,15}$/;
        var obj = $(this).val();
        if (!reg.test(obj)) {
            $(this).attr("style", " border-color: red;");
            $(this).parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");

        }
    });

    $("#UserPassword1").focus(function () {
        $(this).removeAttr("style");
        $(this).parent().next().attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
    });
    $("#UserPassword1").blur(function () {
        var pwd = $("#UserPassword").val();
        var pwd1 = $("#UserPassword1").val();
        var obj = $(this).val();
        if (pwd != pwd1) {
            $(this).attr("style", " border-color: red;");
            $(this).parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");

        }
    });

    $("#UserPhone").focus(function () {
        $(this).removeAttr("style");
        $(this).parent().next().attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
    });
    $("#UserPhone").blur(function () {
        var reg = /^1[358]\d{9}$/;
        var reg170 = /^170\d{8}$/;
        var obj = $(this).val();
        if (obj != "")
            if (!reg.test(obj) && !reg170.test(obj)) {
                $(this).attr("style", " border-color: red;");
                $(this).parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");

            }
    });

    //5.3  新增保存
    $("#but_saveadd").click(function () {
        var NickName = $("#NickName").val();
        var userGroupID = $("#userGroupID").select2("val");
        var UserName = $("#UserName").val();
        var UserPassword = $("#UserPassword").val();
        var UserPassword1 = $("#UserPassword1").val();
        var Description = $("#Description").val();



        var flag = true;
        var msg = "";
        if (1 == 1) {
            var reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]{2,5}$/;  //长度为2-5的汉英文数字下滑线
            if (!reg.test(NickName)) {
                flag = false;
                $("#NickName").attr("style", " border-color: red;");
                $("#NickName").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
                msg = "用户名填写错误（长度为2-5的汉英文数字下滑线）";
            }
        }
        if (1 == 1&&flag) {
            if (userGroupID.length==0) {
                //$("#userGroupID").attr("style", " border-color: red;");
                //$("#userGroupID").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
                $.gritter.add({
                    title: '消息提醒',
                    text: "请选择所属用户组！",
                    class_name: 'gritter-info gritter-center'
                });
                return;
            }
        }
        if (1 == 1 && flag) {
            var reg = /^[a-zA-Z]{3,16}$/;
            if (!reg.test(UserName)) {
                flag = false;
                $("#UserName").attr("style", " border-color: red;");
                $("#UserName").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
                msg = "登陆账号填写错误（长度为3-16个英文）";
            }
        }
        if (1 == 1&&flag) {
            var reg = /^\w{6,15}$/;
            if (!reg.test(UserPassword)) {
                flag = false;
                $("#UserPassword").attr("style", " border-color: red;");
                $("#UserPassword").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
                msg = "密码必须为6-15个字符";
            }
        }
        if (1 == 1&&flag) {
            if (UserPassword != UserPassword1) {
                flag = false;
                $("#UserPassword1").attr("style", " border-color: red;");
                $("#UserPassword1").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
                msg = "两次输入的密码不一致";
            }
        }
        if (!flag) {
            $.gritter.add({
                title: '消息提醒',
                text: msg,
                class_name: 'gritter-info gritter-center'
            });
            return;
        }

        var userType = userGroupID[0]+"";
        for (var i = 1; i < userGroupID.length; i++) {
            userType += "," + userGroupID[i];
        }


        $.ajax({
            url: "AddNewUser",
            dataType: "json",
            Type: "POST",
            data: {
                UserName: NickName,
                userGroupID: userType,
                UserAccount: UserName,
                UserPassword: UserPassword,
                Description: Description
            },
            success: function (data) {
                var json = eval(data);
                if (json.result == "Success") {
                    $("#but_infoclose").click();
                    $.gritter.add({
                        title: '消息提醒',
                        text: json.message,
                        class_name: 'gritter-info gritter-center'
                    });

                    history.go(0);
                }
                else {
                    $.gritter.add({
                        title: '消息提醒',
                        text: json.message,
                        class_name: 'gritter-info gritter-center'
                    });
                }
            }
        });
    });

    //5.5  点击查看密码按钮
    $("#LookPWD").click(function () {
        if ($(this).hasClass("icon-eye-close")) {
            $(this).removeClass("icon-eye-close").addClass("icon-eye-open");
            $("#UserPassword").attr("type", "password");
            $("#UserPassword1").attr("type", "password");
        }
        else {
            $(this).removeClass("icon-eye-open").addClass("icon-eye-close");
            $("#UserPassword").attr("type", "text");
            $("#UserPassword1").attr("type", "text");
        }
    });


    

}

function initForm() {
    $("div#myModal .modal-body .row i:lt(5)").attr("class", "icon-lightbulb tooltip-success cuitooltip form-success");
    $("div#myModal .modal-body .row input:not([autocomplete])").val("").removeAttr("style");
    //$("div#myModal .modal-body .row select:lt(1)").val("0").removeAttr("style");

    $("#but_saveadd").removeAttr("style");
    $("#but_savemodify").removeAttr("style").attr("style", "display:none");

    $("#LookPWD").attr("class", "btn btn-minier btn-white icon-eye-open");
    $("#UserPassword").attr("type", "password")
    $("#UserPassword1").attr("type", "password")

    //初始化多选框
    $("#userGroupID").select2("val", "");
}

//5.4  修改
//5.41 修改初始化
//$("#sample-table-2 i.icon-pencil").click(function () {
$("#sample-table-2 a.modify11").click(function () {
    //改成下拉列表多了一个parent（）
    var id = $(this).parent().parent().parent().parent().parent().children().eq(1).text()
    initForm();
    $.ajax({
        url: "LoadUserModify",
        datatype: "json",
        type: "post",
        data: {
            id: id
        },
        success: function (data) {
            var json = eval(data);
            $("#idHidden").val(json.UserID);
            $("#NickName").val(json.UserName);
            $("#userGroupID").select2("val", json.userGroupID.split(","));
            $("#UserName").val(json.UserAccount);
            $("#UserPassword").val(json.UserPassword);
            $("#UserPassword1").val(json.UserPassword);
            $("#Description").val(json.Description);

            $("#but_saveadd").attr("style", "display:none");
            $("#but_savemodify").removeAttr("style");
            $("#myModal").modal();
        }

    });
});
//5.42 保存修改
$("#but_savemodify").click(function () {
    var UserID = $("#idHidden").val();
    var NickName = $("#NickName").val();
    var userGroupID = $("#userGroupID").select2("val");
    var UserName = $("#UserName").val();
    var UserPassword = $("#UserPassword").val();
    var UserPassword1 = $("#UserPassword1").val();
    var Description = $("#Description").val();

    var flag = true;
    var msg = "";
    if (1 == 1) {
        var reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]{2,5}$/;  //长度为2-5的汉英文数字下滑线
        if (!reg.test(NickName)) {
            flag = false;
            $("#NickName").attr("style", " border-color: red;");
            $("#NickName").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
            msg = "用户名填写错误（长度为2-5的汉英文数字下滑线）";
        }
    }
    if (1 == 1 && flag) {
        if (userGroupID.length == 0) {
            //$("#userGroupID").attr("style", " border-color: red;");
            //$("#userGroupID").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
            $.gritter.add({
                title: '消息提醒',
                text: "请选择所属用户组！",
                class_name: 'gritter-info gritter-center'
            });
            return;
        }
    }
    if (1 == 1 && flag) {
        var reg = /^[a-zA-Z]{3,16}$/;
        if (!reg.test(UserName)) {
            flag = false;
            $("#UserName").attr("style", " border-color: red;");
            $("#UserName").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
            msg = "登陆账号填写错误（长度为3-16个英文）";
        }
    }
    if (1 == 1 && flag) {
        var reg = /^\w{6,15}$/;
        if (!reg.test(UserPassword)) {
            flag = false;
            $("#UserPassword").attr("style", " border-color: red;");
            $("#UserPassword").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
            msg = "密码必须为6-15个字符";
        }
    }
    if (1 == 1 && flag) {
        if (UserPassword != UserPassword1) {
            flag = false;
            $("#UserPassword1").attr("style", " border-color: red;");
            $("#UserPassword1").parent().next().attr("class", "icon-lightbulb cuitooltip tooltip-error icon-animated-vertical red");
            msg = "两次输入的密码不一致";
        }
    }
    if (!flag) {
        $.gritter.add({
            title: '消息提醒',
            text: msg,
            class_name: 'gritter-info gritter-center'
        });
        return;
    }


    var userType = userGroupID[0] + "";
    for (var i = 1; i < userGroupID.length; i++) {
        userType += "," + userGroupID[i];
    }

    $.ajax({
        url: "SaveModifyUser",
        dataType: "json",
        Type: "POST",
        data: {
            id: UserID,
            NickName: NickName,
            userGroupID: userType,
            UserName: UserName,
            UserPassword: UserPassword,
            Description: Description
        },
        success: function (data) {
            var json = eval(data);
            if (json.result == "Success") {
                $("#but_infoclose").click();
                $.gritter.add({
                    title: '消息提醒',
                    text: json.message,
                    class_name: 'gritter-info gritter-center'
                });
                setTimeout(history.go(0), 1000);
            }
            else {
                $.gritter.add({
                    title: '消息提醒',
                    text: json.message,
                    class_name: 'gritter-info gritter-center'
                });
            }
        }
    });
});


//5.6 权限分配
//$(".showInfo").click(function () {
$("#sample-table-2 a.seperate11").click(function () {
    //改为下拉列表多了两个parent（）
    var id = $(this).parent().parent().parent().parent().parent().children().eq(1).text();
    getTree(id);
    $("#idTreeHidden").val(id);
    $("#myTreeModal").modal();
});
//5.6.1 创建权限树
function getTree(userID) {
    var setting = {
        check: {
            enable: true,
            chkboxType: { "Y": "ps", "N": "ps" }
        }, data: {
            simpleData: {
                enable: true
            },
            key: {
                checked: "Checked"
            }
        },

        async: {
            enable: true,
            url: "ShowZTreeList?id=" + userID,
            type: "post"
        }


    };

    var code;

    function setCheck() {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        py = $("#py").attr("checked") ? "p" : "",
        sy = $("#sy").attr("checked") ? "s" : "",
        pn = $("#pn").attr("checked") ? "p" : "",
        sn = $("#sn").attr("checked") ? "s" : "",
        type = { "Y": py + sy, "N": pn + sn };
        zTree.setting.check.chkboxType = type;
        showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
    }
    function showCode(str) {
        if (!code) code = $("#code");
        code.empty();
        code.append("<li>" + str + "</li>");
    }

    $(document).ready(function () {
        $.fn.zTree.init($("#treeDemo"), setting, null);
        //setCheck();
        //$("#py").bind("change", setCheck);
        //$("#sy").bind("change", setCheck);
        //$("#pn").bind("change", setCheck);
        //$("#sn").bind("change", setCheck);
    });
}
//5.6.2 点击保存将所选序列号以及本身角色Id传回服务器
$("#but_savetree").click(function () {
    var nodes = onCheck();
    var id = $("#idTreeHidden").val();
    $.ajax({
        url: "SaveTree",
        dataType: "json",
        data: {
            id: id,
            nodes: nodes
        },
        Type: "post",
        success: function (data) {
            var json = eval(data);
            if (json.result == "Success") {
                $.gritter.add({
                    title: '消息提醒',
                    text: json.message,
                    class_name: 'gritter-info gritter-center'
                });
                $("#but_infoclose").click();
                setTimeout(function () {
                    history.go(0)
                }, 3000);

            }
            else {
                $.gritter.add({
                    title: '消息提醒',
                    text: json.message,
                    class_name: 'gritter-info gritter-center'
                });
            }

        }
    });
});

//5.6.3 获取所有选中的节点
function onCheck(e, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
    nodes = treeObj.getCheckedNodes(true),
    v = "";
    if (nodes.length == 0) { return ""; }
    var ids = nodes[0].id;
    for (var i = 1; i < nodes.length; i++) {
        v += nodes[i].name;
        //alert(nodes[i].id); //获取选中节点的值
        ids += "," + nodes[i].id;
    }
    return ids;

}